import React, { Component } from 'react';
import * as RecordAPI from '../api/RecordAPI'

class Form extends Component {
  constructor(props) {
    super(props)
    this.state = {
      date: '',
      title: '',
      amount: ''
    }
  }
  valid() {
    return this.state.date && this.state.title && this.state.amount
  }
  handleChange = (event) => {
    let name, obj;
    name = event.target.name
    this.setState((
      obj = {},
      obj['' + name] = event.target.value,
      obj
    ))
  }
  handleSubmit = (event) => {
    event.preventDefault()
    RecordAPI.create(this.state).then(res => {
      this.props.handleNewRecord(res.data)
      this.setState({
        date: '',
        title: '',
        amount: ''
      })
    }).catch(error => {
      console.log(error)
    })
  }
  render() {
    return (
      <form className="form-inline " onSubmit={this.handleSubmit.bind(this)}>
        <div className="form-group mr-1 mb-3">
          <input type="text" name="date" className="form-control" placeholder="Date" onChange={this.handleChange} value={this.state.date}/>
        </div>
        <div className="form-group mr-1 mb-3">
          <input type="text" name="title" className="form-control" placeholder="title" onChange={this.handleChange} value={this.state.title}/>
        </div>
        <div className="form-group mr-1 mb-3">
          <input type="text" name="amount" className="form-control" placeholder="amount" onChange={this.handleChange} value={this.state.amount}/>
        </div>
        <button type="submit" className="btn btn-primary mb-3" disabled={!this.valid()} onClick={this.handleSubmit}>Create Record</button>
      </form>
    );
  }
}

export default Form;
